package raceReservationServer.raceServerGateway;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import JMSRaceServer.RaceJMSDTO;

public class JMSRaceServerGateway implements IRaceServerGateway 
{
	private String serviceUri;
	private String serverName;
	
	//atributes to receive the JMS messages
	private String queueName = null;
	private Context jndiContext = null;
	private QueueConnectionFactory queueConnectionFactory = null;
	private QueueConnection queueConnection = null;
	private QueueSession queueSession = null;
	private Queue queue = null;
	private QueueReceiver queueReceiver = null;
	private TextMessage textMessage = null;
	private ObjectMessage objectMessage = null;
	
	public JMSRaceServerGateway(String serviceUri) 
	{
		//StringTokenizer tokens = new StringTokenizer(serviceUri);
		//this.serviceUri = tokens.nextToken();
		//this.serverName = tokens.nextToken(); 
		this.serviceUri = "allRunnersQueue";
		this.serverName = "NafarroaRaces";
		System.out.println(serviceUri);
		System.out.println(serverName);
	}

	public List<RaceDO> getRaces() {
		List<RaceDO> result = new ArrayList<RaceDO>();
		queueName = serviceUri;	
		//queueName = "allRunnersQueue";
		System.out.println("Queue name is " + queueName);
		try
		{
			Properties props = new Properties();
			props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
			props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61616");
			props.load(new FileInputStream("jndi.properties"));
			jndiContext = new InitialContext(props);
		}
		catch (NamingException e) 
		{
			System.out.println("Could not create JNDI API context: " + e.toString());
			System.exit(1);
		}
		catch(IOException ioe)
		{
			System.out.println("Could not find properties file: " + ioe.toString());
			System.exit(1);
		}
		try
		{
			queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
			queue = (Queue) jndiContext.lookup(queueName);
		}
		catch (NamingException e)
		{
			System.out.println("JNDI API lookup failed: " + e.toString());
			System.exit(1);
		}
		try
		{
			queueConnection = queueConnectionFactory.createQueueConnection();
			queueSession = queueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
			if(queueSession==null)
			{
				System.out.println("queueSession==null");
			}
			queueReceiver = queueSession.createReceiver(queue);
			queueConnection.start();
			while (true)
			{
				Message m = queueReceiver.receive(1);
				if (m != null)
				{
					if (m instanceof TextMessage)
					{
						textMessage = (TextMessage) m;
						System.out.println("Reading message: " + textMessage.getText());
					}
					else if (m instanceof ObjectMessage)
					{
						objectMessage = (ObjectMessage) m;
						RaceJMSDTO race = (RaceJMSDTO) objectMessage.getObject();
						System.out.println("Reading message: " + race.getName());
						result.add(new RaceDO(race.getName(), race.getDistance(),race.getDate(), race.getAvailablePlaces()));
					}
					else {break;}
				}
			}
		}
		catch (JMSException e)
		{
			System.out.println("Exception occurred: " + e.toString());
		}
		finally
		{
			if (queueConnection != null) {
				try
				{
					queueConnection.close();
				}
				catch (JMSException e) {}
			}
		}
	//--------------------------------------------------------------------
		return result;
	}

	@Override
	public String getServer() 
	{ 
		return serverName;
	}	
	/*public static void main(String[] args)
	{
		JMSRaceServerGateway jmsgate = new JMSRaceServerGateway("hola");
		List<RaceDO> list = jmsgate.getRaces();
		if (list == null)
		{
			System.out.println("list==null");
		}
		else
		{
			for(int i=0; i< list.size();i++)
			{
				System.out.println(list.get(i).getName() + list.get(i).getDistance());
			}
		}	
	}*/
}
